package com.hmjk.health.background.data;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.text.format.Time;
import android.util.Log;

import com.hmjk.health.HealthApp;
import com.hmjk.health.background.DataManager;
import com.hmjk.health.background.DatabaseHelper;
import com.hmjk.health.background.NetService;

public class FamilyMemberUpdated extends DataUpdated{
	private static String TAG = FamilyMemberUpdated.class.getSimpleName();
	private ArrayList<String> mFids = new ArrayList<String>();
	private int current = 0;
	private boolean working = false;
	
	private void logd(String info){
		Log.d(TAG, info);
	}
	
	public FamilyMemberUpdated(HealthApp app, DataManager dm, DataUpdated base) {
		super(app, dm, base);
		UPDATE_TIME = 2 * 60 * 60 * 1000;
	}

	@Override
	public void setUserData(Object data) {
		// TODO Auto-generated method stub
		reqTime = 0;
	}

	@Override
	public long delay() {
		long curMs = System.currentTimeMillis();
		long del = curMs - upTime;
		logd("delay curMs="+curMs+" upTime="+upTime+" del="+del);
		if(del >= UPDATE_TIME){
			logd("delay 0");
			return 0;
		}else{
			logd("delay (UPDATE_TIME - del) = "+(UPDATE_TIME - del));
			return (UPDATE_TIME - del);
		}
	}

	private void getFids(){
		String[] args = new String[1];
		args[0] = new String("FID");
		
		JSONObject fidsJson = (JSONObject) mBaseData.check(args);
		
		mFids.clear();
		if(fidsJson != null){
			try {
				JSONArray ar = fidsJson.getJSONArray("array");
				int len = ar.length();
				for(int i = 0; i < len; i++){
					JSONObject e = ar.getJSONObject(i);
					String fid = e.getString("fid");
					if((fid != null) && (fid.trim().isEmpty() == false)){
						mFids.add(fid);
					}
				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}	
	}
	
	private void doNextRequest(){
		String uid = mApp.getUID();
		if(uid == null){
			Log.e(TAG, "doNextRequest uid == null stoped!");
			working = false;
		}
		int size = mFids.size();
		if(current < size){
			working = true;
			String fid = mFids.get(current);
			Intent si = new Intent(NetService.GET_DATA_ACTION);
			si.putExtra("sub_act", NetService.GET_FAMILY_MEMBER);
			si.putExtra("uid", uid);
			si.putExtra("fid", fid.trim());
			Time t = new Time();
			t.setToNow();
			String stamp = "GET_FAMILY_MEMBER" + t.toString(); 
			si.putExtra("stamp",stamp);
			mApp.addNetHandler(stamp,mDm.getBackGroundHandler());
			mApp.startService(si);
			current ++;
		}else{
			working = false;
		}
	}
	
	private void doRequest(String uid){	
		getFids();
		current = 0;
		logd("doRequest size=" + mFids.size());
		if(mFids.size() > 0){
			doNextRequest();
		}else{
			Intent i = new Intent(DataManager.DATA_UPDATE_ACTION);
			i.putExtra("type",DataManager.F_FAMILYMEMBER);
			i.putExtra("state", false);
			i.putExtra("fid", "");
			mApp.sendBroadcast(i);
		}
	}
	
	@Override
	public boolean grab() {
		String uid = mApp.getUID();
		logd("grab uid="+uid);
		if(uid == null)
			return false;
		
		if(working){
			logd("grab working now");
			return false;
		}
		
		long curMs = System.currentTimeMillis();
		logd("grab curMs="+curMs+" reqTime="+reqTime);
		if((curMs - reqTime) > UPDATE_TIME){
			doRequest(uid);
			reqTime = curMs;
			logd("grab req sent!");
			return true;
		}
		return false;
	}

	@Override
	public boolean grabByUser() {
		String uid = mApp.getUID();
		logd("grabByUser uid="+uid);
		if(uid == null)
			return false;
		
		if(working){
			logd("grab working now");
			return false;
		}
		
		long curMs = System.currentTimeMillis();
		logd("grabByUser curMs="+curMs+" reqTime="+reqTime);
		if((curMs - reqTime) > 30 * 1000){
			doRequest(uid);
			reqTime = curMs;
			logd("grabByUser req sent!");
			return true;
		}
		return false;
	}

	@Override
	public void receive(String stamp, String sjson) {
		DatabaseHelper dh = mDm.getDatabaseHelper();
		if(dh == null)
			return;
		
		if(stamp.startsWith("GET_FAMILY_MEMBER")){
			
			if(sjson != null){
				boolean update = false;
				String checkFid = "";
				try {
					JSONObject json = new JSONObject(sjson);
					int code = json.getInt("code");
					if(code == 200){
						String state = json.getString("state");
						if(state.equals("00")){
							JSONObject sd = json.getJSONObject("senddata");
							JSONObject recdata = json.getJSONObject("recdata");
							if(recdata != null){
								checkFid = sd.getString("fid");
								dh.clearFaMemberTableByFid(checkFid);
								JSONArray array = null;
								upTime = System.currentTimeMillis();
								if(recdata.has("uidarray")){
									array = recdata.getJSONArray("uidarray");
								}
								if((array != null) && (array.length() > 0)){
									for(int index = 0; index < array.length(); index ++){
										JSONObject o = array.getJSONObject(index);
										ContentValues cv = new ContentValues();
										String uid = o.getString("uid");
										cv.put(DatabaseHelper.FAMEMBERS_UID, uid);
										cv.put(DatabaseHelper.FAMEMBERS_FID, checkFid);
										String name = "";
										if(o.has("username")){
											name = o.getString("username").trim();
										}
										cv.put(DatabaseHelper.FAMEMBERS_NAME, name);
										String status = "";
										if(o.has("familystatus")){
											status = o.getString("familystatus");
										}
										cv.put(DatabaseHelper.FAMEMBERS_STATUS, status);
										
										String build = "0";
										if(o.has("build")){
											build = o.getString("build");
											if(build.equals("0") || build.equals("1")){
												
											}else{
												build = "0";
											}
										}
										cv.put(DatabaseHelper.FAMEMBERS_BUILD, build);
										
										String admin = "0";
										if(o.has("admin")){
											admin = o.getString("admin");
											if(admin.equals("0") || admin.equals("1")){
												
											}else{
												admin = "0";
											}
										}
										cv.put(DatabaseHelper.FAMEMBERS_ADMIN, admin);
										cv.put(DatabaseHelper.FAMEMBERS_TIME, upTime);
										dh.addOneItem2FaMemberTable(cv);
									}
								}
								dh.closeDB();
								update = true;
							}
						}
					}
				}catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} 
				
				doNextRequest();
				Intent i = new Intent(DataManager.DATA_UPDATE_ACTION);
				i.putExtra("type",DataManager.F_FAMILYMEMBER);
				i.putExtra("state", update);
				i.putExtra("fid", checkFid);
				mApp.sendBroadcast(i);
			}
		}else if(stamp.startsWith("COMMIT_ADMIN_FA")){
			
			if(sjson != null){
				String state = "af";
				int code = 400;
				String fid = "";
				String uid = "";
				try {
					JSONObject json = new JSONObject(sjson);
					code = json.getInt("code");
					if(code == 200){
						state = json.getString("state");

						if(state.equals("00")){
							upTime = System.currentTimeMillis();
							JSONObject sd = json.getJSONObject("senddata");
							fid = sd.getString("fid");
							uid = sd.getString("adminuid");
							String old = sd.getString("oldadminuid");
							
							if(old.trim().isEmpty() == false){
								Cursor c = dh.queryOneFamilyMemberData(fid, old);
								if((c != null) && (c.getCount() > 0)){
									c.moveToFirst();
									String name = c.getString(c.getColumnIndex(DatabaseHelper.FAMEMBERS_NAME));
									String status = c.getString(c.getColumnIndex(DatabaseHelper.FAMEMBERS_STATUS));
									String build = c.getString(c.getColumnIndex(DatabaseHelper.FAMEMBERS_BUILD));
									
									ContentValues cv = new ContentValues();
									
									cv.put(DatabaseHelper.FAMEMBERS_FID, fid);
									cv.put(DatabaseHelper.FAMEMBERS_UID, old);
									cv.put(DatabaseHelper.FAMEMBERS_NAME, name);
									cv.put(DatabaseHelper.FAMEMBERS_STATUS, status);
									cv.put(DatabaseHelper.FAMEMBERS_BUILD, build);
									cv.put(DatabaseHelper.FAMEMBERS_ADMIN, "0");
									cv.put(DatabaseHelper.FAMEMBERS_TIME, upTime);
									dh.updateOneItemInFaMember(fid, old, cv);
								}
								if(c != null)
									c.close();
							}
							
							Cursor c = dh.queryOneFamilyMemberData(fid, uid);
							if((c != null) && (c.getCount() > 0)){
								c.moveToFirst();
								String name = c.getString(c.getColumnIndex(DatabaseHelper.FAMEMBERS_NAME));
								String status = c.getString(c.getColumnIndex(DatabaseHelper.FAMEMBERS_STATUS));
								String build = c.getString(c.getColumnIndex(DatabaseHelper.FAMEMBERS_BUILD));
								
								ContentValues cv = new ContentValues();
								cv.put(DatabaseHelper.FAMEMBERS_FID, fid);
								cv.put(DatabaseHelper.FAMEMBERS_UID, uid);
								cv.put(DatabaseHelper.FAMEMBERS_NAME, name);
								cv.put(DatabaseHelper.FAMEMBERS_STATUS, status);
								cv.put(DatabaseHelper.FAMEMBERS_BUILD, build);
								cv.put(DatabaseHelper.FAMEMBERS_ADMIN, "1");
								cv.put(DatabaseHelper.FAMEMBERS_TIME, upTime);
								dh.updateOneItemInFaMember(fid, uid, cv);
							}
							if(c != null)
								c.close();
							
							dh.closeDB();
						}
					}
				}catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				Intent i = new Intent(DataManager.DATA_COMMIT_RESULT);
				i.putExtra("type",DataManager.F_FAMILYMEMBER);
				i.putExtra("action", "set_admin");
				i.putExtra("fid", fid);
				i.putExtra("state", state);
				i.putExtra("code", code);
				i.putExtra("adminUid", uid);
				mApp.sendBroadcast(i);
			}
		}else if(stamp.startsWith("COMMIT_ABORT_BY_ADMIN_FA")){
			if(sjson != null){
				String state = "af";
				int code = 400;
				String checkFid = "";
				try {
					JSONObject json = new JSONObject(sjson);
					code = json.getInt("code");
					if(code == 200){
						state = json.getString("state");
						if(state.equals("00")){
							JSONObject sd = json.getJSONObject("senddata");
							checkFid = sd.getString("fid");
							JSONArray uidarray = sd.getJSONArray("uidarray");
							int len = uidarray.length();
							for(int i = 0; i < len; i++){
								String memUid = uidarray.getString(i);
								dh.delateOneItemInFaMemberTable(checkFid, memUid);
							}
							upTime = System.currentTimeMillis();
							dh.closeDB();
						}
					}
				}catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				Intent i = new Intent(DataManager.DATA_COMMIT_RESULT);
				i.putExtra("type",DataManager.F_FAMILYMEMBER);
				i.putExtra("action", "abort");
				i.putExtra("fid", checkFid);
				i.putExtra("state", state);
				i.putExtra("code", code);
				mApp.sendBroadcast(i);
			}
		}
		
	}

	@Override
	public Object check(String[] arg) {
		JSONObject ret = null;
		DatabaseHelper dh = mDm.getDatabaseHelper();
		if(dh == null)
			return null;
		if(arg == null){
			//return all
		Cursor c = dh.queryFamilyMemberTableData();
		try {
			ret = new JSONObject();
			if(c.getCount() > 0){
				JSONArray array = new JSONArray();
				while(c.moveToNext()){
					String uid = c.getString(c.getColumnIndex(DatabaseHelper.FAMEMBERS_UID));
					String fid = c.getString(c.getColumnIndex(DatabaseHelper.FAMEMBERS_FID));
					String name = c.getString(c.getColumnIndex(DatabaseHelper.FAMEMBERS_NAME));
					String status = c.getString(c.getColumnIndex(DatabaseHelper.FAMEMBERS_STATUS));
					String admin = c.getString(c.getColumnIndex(DatabaseHelper.FAMEMBERS_ADMIN));
					String build = c.getString(c.getColumnIndex(DatabaseHelper.FAMEMBERS_BUILD));
					upTime = c.getLong(c.getColumnIndex(DatabaseHelper.FAMEMBERS_TIME));
					JSONObject e = new JSONObject();
					e.put("uid", uid);
					e.put("fid", fid);
					e.put("name", name);
					e.put("status", status);
					e.put("admin", admin);
					e.put("build", build);
					array.put(e);
				}
				ret.put("array", array);
				ret.put("uptime", upTime);
			}else{
				JSONArray array = new JSONArray();
				ret.put("array", array);
				ret.put("uptime", upTime);
			}
		} catch (JSONException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			ret = null;
		}
		c.close();
		dh.closeDB();
		}else if(arg[0].length() > 0){
			/*
			Cursor c = dh.queryOneFamilyMemberData(arg[0]);
			if((c != null) && (c.getCount() > 0)){
				c.moveToFirst();
				try {
					ret = new JSONObject();
					String uid = c.getString(c.getColumnIndex(DatabaseHelper.FAMEMBERS_UID));
					String fid = c.getString(c.getColumnIndex(DatabaseHelper.FAMEMBERS_FID));
					String name = c.getString(c.getColumnIndex(DatabaseHelper.FAMEMBERS_NAME));
					String status = c.getString(c.getColumnIndex(DatabaseHelper.FAMEMBERS_STATUS));
					String admin = c.getString(c.getColumnIndex(DatabaseHelper.FAMEMBERS_ADMIN));
					String build = c.getString(c.getColumnIndex(DatabaseHelper.FAMEMBERS_BUILD));
					upTime = c.getLong(c.getColumnIndex(DatabaseHelper.FAMEMBERS_TIME));
					ret.put("uid", uid);
					ret.put("fid", fid);
					ret.put("name", name);
					ret.put("status", status);
					ret.put("admin", admin);
					ret.put("build", build);
				}catch (JSONException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
					ret = null;
				}
			}
			if(c != null)
				c.close();
			dh.closeDB();
			*/
		}
		return ret;
	}

	@Override
	public boolean commit(Object data) {
		DatabaseHelper dh = mDm.getDatabaseHelper();
		if(dh == null)
			return false;
		
		String uid = mApp.getUID();
		
		if((uid == null) || uid.isEmpty())
			return false;
			
		JSONObject json = (JSONObject)data;
		if(json == null)
			return false;
		
		try {
			String cmd = json.getString("cmd");
			
			if(cmd.equalsIgnoreCase("setadmin")){
				Intent si = new Intent(NetService.COMMIT_DATA_ACTION);
				
				Time t = new Time();
				t.setToNow();
				String stamp = null;
				si.putExtra("sub_act", NetService.COMMIT_ADMIN_FA);
				stamp = "COMMIT_ADMIN_FA" + t.toString(); 
				si.putExtra("stamp",stamp);
				
				si.putExtra("uid", uid);
				String fid = json.getString("fid");
				si.putExtra("fid", fid);
				String adminuid = json.getString("adminuid");
				si.putExtra("adminuid", adminuid);
				String oldadminuid = json.getString("oldadminuid");
				si.putExtra("oldadminuid", oldadminuid);
				
				mApp.addNetHandler(stamp,mDm.getBackGroundHandler());
				mApp.startService(si);
			}else if(cmd.equalsIgnoreCase("abortbyadmin")){
				Intent si = new Intent(NetService.COMMIT_DATA_ACTION);
				
				Time t = new Time();
				t.setToNow();
				String stamp = null;
				si.putExtra("sub_act", NetService.COMMIT_ABORT_BY_ADMIN_FA);
				stamp = "COMMIT_ABORT_BY_ADMIN_FA" + t.toString(); 
				si.putExtra("stamp",stamp);
				
				si.putExtra("uid", uid);
				String fid = json.getString("fid");
				si.putExtra("fid", fid);
				JSONArray uidarray = json.getJSONArray("uidarray");
				si.putExtra("uidarray", uidarray.toString());
				
				mApp.addNetHandler(stamp,mDm.getBackGroundHandler());
				mApp.startService(si);
			}else if(cmd.equalsIgnoreCase("quit")){
				String fidDel = json.getString("fid");
				dh.clearFaMemberTableByFid(fidDel);
				dh.closeDB();
			}
			
			return true;
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return false;
	}
	
	@Override
	public void release() {
		// TODO Auto-generated method stub
		
	}
}
